package com.wei.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wei.entity.Subject;
import com.wei.entity.excel.SubjectData;
import com.wei.listener.SubjectExcelListener;
import com.wei.service.SubjectService;
import com.wei.mapper.SubjectMapper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author HASEE
 * @description 针对表【edu_subject(课程科目)】的数据库操作Service实现
 * @createDate 2022-11-23 09:57:54
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject>
        implements SubjectService {

    @Override
    public void saveSubject(MultipartFile file) {
        try {
            //文件输入流
            InputStream is = file.getInputStream();

            //调用方法进行读取
            EasyExcel.read(is, SubjectData.class, new SubjectExcelListener(this)).sheet().doRead();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Subject> getAllSubject() {
        List<Subject> list = list();
        List<Subject> subjectList = list.stream()
                .filter(subject ->
                        subject.getParentId().equals("0")
                ).map(subject -> {
                    //找到子菜单
                    LambdaQueryWrapper<Subject> subjectWrapper = new LambdaQueryWrapper<>();
                    subjectWrapper.eq(Subject::getParentId, subject.getId());
                    subject.setChildren(baseMapper.selectList(subjectWrapper));
                    return subject;
                }).sorted((subject1, subject2) -> {
                    return (subject1.getSort() == null ? 0 : subject1.getSort()) - (subject2.getSort() == null ? 0 : subject2.getSort());
                }).collect(Collectors.toList());
        return subjectList;
    }
}




